package books.borrowing.dao.impl;

/**
 * NOUVELLE METHODE
 */

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;

import books.borrowing.EJBFacade;
import books.borrowing.bo.ISubscriberBo;
import books.borrowing.dao.IBookBorrowingDao;
import books.borrowing.entity.BookBorrowingEntity;
import books.borrowing.util.CustomHibernateDaoSupport;

@Repository("rentDao")
public class BookBorrowingDao extends CustomHibernateDaoSupport implements IBookBorrowingDao {

	private ISubscriberBo _sub;
	
	public void save(BookBorrowingEntity _rent) throws Exception {
		_rent.setRentDate(new Date());
		
		if(_rent.getSubscriber() == null) throw new Exception("Emprunteur non renseigné !");
		
		getHibernateTemplate().saveOrUpdate(_rent);
	}

	public void update(BookBorrowingEntity _rent) {
		getHibernateTemplate().update(_rent);
	}

	public void delete(BookBorrowingEntity _rent) {
		getHibernateTemplate().delete(_rent);
	}

	public BookBorrowingEntity rentBook(String _login, String _ISBN) throws Exception {
		BookBorrowingEntity rent = new BookBorrowingEntity();
		rent.setBookISBN(_ISBN);
		
		EJBFacade.getInstance();
		_sub = EJBFacade.getSubscriberBo();
		rent.setSubscriber(_sub.findSubscriberByLogin(_login));
		
		this.save(rent);
		
		return rent;
	}

	public BookBorrowingEntity returnBook(String _login, String _ISBN) {
		for(BookBorrowingEntity rentBook : this.findRent(_login, _ISBN)) {
			if(rentBook.getReturnDate() == null) {
				rentBook.setReturnDate(new Date());
				this.update(rentBook);
				return rentBook;
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<BookBorrowingEntity> findRent(String _login, String _ISBN) {	
		List<BookBorrowingEntity> rentList = getHibernateTemplate().find("from BookBorrowingEntity where bookISBN = ? and subscriber.login = ? ", _ISBN, _login);
		return rentList;
	}

	@SuppressWarnings("unchecked")
	public List<BookBorrowingEntity> findSubscriberRents(String _login) {
		List<BookBorrowingEntity> subRents = getHibernateTemplate().find("from BookBorrowingEntity where subscriber.login = ?", _login);
		return subRents;
	}
}
